package xyz.xiangyushui.controller.authentication;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import xyz.xiangyushui.dao.employee.EmployeeDao;
import xyz.xiangyushui.dao.user.member.MembershipDao;
import xyz.xiangyushui.javaBean.user.User;

/**
 * Servlet implementation class Router
 */
@WebServlet("/router")
public class Router extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private EmployeeDao ed;
	private MembershipDao md;
	
	
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Router() {
		super();
		ed=new EmployeeDao();
		md=new MembershipDao();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		User user = (User) request.getSession(false).getAttribute("user");
		//System.out.println(user.getRole());
		switch (user.getRole()) {
		case member:
			switch(md.getState(user.getName())){
			case 0:
				response.sendRedirect(response.encodeURL(request.getContextPath()+"/active"));
				break;
			case 1:response.sendRedirect(response.encodeURL(request.getContextPath()+"/member"));
				break;
			case 2:
				response.sendRedirect(response.encodeURL(request.getContextPath()+"/stop"));
				break;
			}
			
			break;
		case admin:response.sendRedirect(response.encodeURL(request.getContextPath()+"/admin"));
			break;
		case employee:int storeId1=ed.getStoreId(user.getName());
		if(storeId1==0){
			response.getWriter().append("you are not assigned to any store!");
		}else{
			request.getSession(false).setAttribute("storeId",storeId1);
			response.sendRedirect(response.encodeURL(request.getContextPath()+"/employee"));
		}
		break;
		case employeeLeader:
			int storeId=ed.getStoreId(user.getName());
			if(storeId==0){
				response.getWriter().append("you are not assigned to any store!");
			}else{
				request.getSession(false).setAttribute("storeId",storeId);
				response.sendRedirect(response.encodeURL(request.getContextPath()+"/employeeLeader"));
			}
			break;
		case manager:response.sendRedirect(response.encodeURL(request.getContextPath()+"/manager"));
			break;
		default:
			break;
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
